﻿using System;
using System.Collections.Specialized;
using System.Web.Security;
using LightWeb.DomainModel;
using LightWeb.Infrastructure.Repositories;

namespace LightWeb.Application.WebSecurity
{
    public class NHMembershipProvider : MembershipProvider
    {
        IMembershipProviderRepository Repository { get; set; }

        #region Property
        NameValueCollection Config { get; set; }

        string _AppName = string.Empty;
        public override string ApplicationName
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_AppName))
                    _AppName = Config["ApplicationName"];
                return _AppName;
            }
            set { _AppName = value; }
        }

        public override bool EnablePasswordReset
        {
            get
            {
                return string.Equals(Config["ApplicationName"], "true");
            }
        }

        public override bool EnablePasswordRetrieval
        {
            get
            {
                return string.Equals(Config["EnablePasswordRetrieval"], "true");
            }
        }

        public override int MaxInvalidPasswordAttempts
        {
            get
            {
                return GetConfigValue("EnablePasswordRetrieval");
            }
        }

        int GetConfigValue(string configFields)
        {
            int v = 0;
            int.TryParse(Config[configFields], out v);
            return v;
        }



        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return GetConfigValue("MinRequiredNonAlphanumericCharacters"); }
        }

        public override int MinRequiredPasswordLength
        {
            get { return GetConfigValue("MinRequiredPasswordLength"); }
        }

        public override int PasswordAttemptWindow
        {
            get { return GetConfigValue("PasswordAttemptWindow"); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get
            {
                MembershipPasswordFormat v = MembershipPasswordFormat.Clear;
                Enum.TryParse<MembershipPasswordFormat>(Config["PasswordFormat"], out v);
                return v;
            }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { return Config["PasswordStrengthRegularExpression"]; }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { return string.Equals(Config["EnablePasswordRetrieval"], "true"); }
        }

        public override bool RequiresUniqueEmail
        {
            get { return string.Equals(Config["EnablePasswordRetrieval"], "true"); }
        }

        #endregion

        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            base.Initialize(name, config);
            this.Config = config;
            Repository = new SecurityService();
        }

        #region Method
        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            return Repository.ChangePassword(username, oldPassword, newPassword);
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            return Repository.ChangePasswordQuestionAndAnswer(username, password, newPasswordQuestion, newPasswordAnswer);
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            Repository.CreateUser(new User
            {
                LoginName = username,
                DisplayName = username,
                FirstName = username,
                Email = email,
                Password = password,
                IsApproved = isApproved,
                PasswordAnswer = passwordAnswer,
                PasswordQuestion = passwordQuestion,
                ProviderUserKey = providerUserKey
            });
            MembershipUser user = this.GetMembershipUser(username, email, DateTime.Now);
            status = MembershipCreateStatus.Success;
            return user;
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            return Repository.DelteUser(username, deleteAllRelatedData);
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection users = new MembershipUserCollection();
            var result = Repository.FindUsersByEmail(emailToMatch, pageIndex, pageSize);
            totalRecords = result.TotalListCount;
            foreach (var item in result.ModelList)
            {
                users.Add(item);
            }
            return users;
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection users = new MembershipUserCollection();
            PagerContent<MembershipUser> result = Repository.FindUsersByName(usernameToMatch, pageIndex, pageSize);
            totalRecords = result.TotalListCount;
            foreach (var item in result.ModelList)
            {
                users.Add(item);
            }
            return users;
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection users = new MembershipUserCollection();
            PagerContent<MembershipUser> result = Repository.GetAllUsers(pageIndex, pageSize);
            totalRecords = result.TotalListCount;
            foreach (var item in result.ModelList)
            {
                users.Add(item);
            }
            return users;
        }

        public override int GetNumberOfUsersOnline()
        {
            return Repository.GetNumberOfUsersOnline();
        }

        public override string GetPassword(string username, string answer)
        {
            return Repository.GetPassword(username, answer);
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            return Repository.GetUser(username, userIsOnline);
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            return Repository.GetUser(providerUserKey, userIsOnline);
        }

        public override string GetUserNameByEmail(string email)
        {
            return Repository.GetUserNameByEmail(email);
        }

        public override string ResetPassword(string username, string answer)
        {
            return Repository.ResetPassword(username, answer);
        }

        public override bool UnlockUser(string userName)
        {
            return Repository.UnlockUser(userName);
        }

        public override void UpdateUser(MembershipUser user)
        {
            Repository.UpdateUser(user);
        }

        public override bool ValidateUser(string username, string password)
        {
            return Repository.ValidateUser(username, password);
        }

        #endregion

        #region Help Function
        private MembershipUser GetMembershipUser(string userName, string email, DateTime lastLogin)
        {
            var user = new MembershipUser(
                this.Name, // Provider name
                userName, // Username
                userName, // providerUserKey
                email, // Email
                string.Empty, // passwordQuestion
                string.Empty, // Comment
                true, // approved
                false, // isLockedOut
                DateTime.Now, // creationDate
                lastLogin, // lastLoginDate
                DateTime.Now, // lastActivityDate
                DateTime.Now, // lastPasswordChangedDate
                new DateTime(1980, 1, 1)); // lastLockoutDate
            return user;
        }
        #endregion
    }
}
